﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace 音乐播放器
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        //用集合来存储文件的全路径
        List<string> fileNamesList = new List<string>();
        /// <summary>
        /// 打开音乐文件路径
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOpenFiles_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Title = "请选择音乐(⊙o⊙)？";
            openFileDialog.Filter = "音乐文件|*.mp3|所有文件|*.*";
            openFileDialog.Multiselect = true;
            openFileDialog.ShowDialog();
            string[] fileNames = openFileDialog.FileNames;
            foreach (string fileName in fileNames)
            {
                fileNamesList.Add(fileName);
                listBoxMusic.Items.Add(Path.GetFileName(fileName));
            }
        }

        /// <summary>
        /// 双击列表 播放音乐
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void listBoxMusic_DoubleClick(object sender, EventArgs e)
        {
            if (listBoxMusic.Items.Count == 0)
            {
                MessageBox.Show("请先选择文件···");
            }
            else
            {
                // 启用按钮 并 初始化
                btnControlMusic.Enabled = true;
                btnStopMusic.Enabled = true;
                btnPreviousSong.Enabled = true;
                btnNextSong.Enabled = true;
                btnControlMusic.Text = "暂停";
                // 播放音乐
                int selectedIndex = listBoxMusic.SelectedIndex;
                MediaPlayer.URL = fileNamesList[selectedIndex];
                MediaPlayer.Ctlcontrols.play();
                // 找到对应的歌词文件
                int index = listBoxMusic.SelectedIndex;
                string fileName = fileNamesList[index];
                string lrcPath = GetLrcFile(fileName);
                // 解析歌词文件 存放在集合中
                if (File.Exists(lrcPath))
                {
                    DoLrcFile(lrcPath);
                }
                else
                {
                    label3.Text = "------------";
                }
            }
        }
        /// <summary>
        /// 字符串操作，获取字符文件
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        private static string GetLrcFile(string fileName)
        {
            string[] newFileName = fileName.Split(new char[] { '.' });
            string lrcPath = newFileName[0] + ".lrc";
            return lrcPath;
        }

        /// <summary>
        /// 控制音乐的播放和暂停
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnControlMusic_Click(object sender, EventArgs e)
        {
            if (btnControlMusic.Text == "暂停")
            {
                MediaPlayer.Ctlcontrols.pause();
                btnControlMusic.Text = "播放";
            }
            else if (btnControlMusic.Text == "播放")
            {
                MediaPlayer.Ctlcontrols.play();
                btnControlMusic.Text = "暂停";
            }
            else
            {

            }
        }

        /// <summary>
        /// 停止音乐的播放
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnStopMusic_Click(object sender, EventArgs e)
        {
            MediaPlayer.Ctlcontrols.stop();
            btnControlMusic.Text = "播放";
        }

        /// <summary>
        /// 上一曲
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnPreviousSong_Click(object sender, EventArgs e)
        {
            // 歌曲总数
            int count = fileNamesList.Count;
            // 当前播放歌曲的index
            int selectedIndex = listBoxMusic.SelectedIndex;
            // 上一曲的index
            int index = selectedIndex - 1;
            if (index < 0)
            {
                index = count - 1;
                MediaPlayer.URL = fileNamesList[index];
                MediaPlayer.Ctlcontrols.play();
            }
            else
            {
                MediaPlayer.URL = fileNamesList[index];
                MediaPlayer.Ctlcontrols.play();
            }
            listBoxMusic.SelectedIndex = index;
        }

        /// <summary>
        /// 下一曲
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnNextSong_Click(object sender, EventArgs e)
        {
            // 歌曲总数
            int count = fileNamesList.Count;
            // 当前播放歌曲的index
            int selectedIndex = listBoxMusic.SelectedIndex;
            // 下一曲的index
            int index = selectedIndex + 1;
            if (index >= count)
            {
                index = 0;
                MediaPlayer.URL = fileNamesList[index];
                DoLrcFile(GetLrcFile(fileNamesList[index]));
                MediaPlayer.Ctlcontrols.play();
            }
            else
            {
                MediaPlayer.URL = fileNamesList[index];
                DoLrcFile(GetLrcFile(fileNamesList[index]));
                MediaPlayer.Ctlcontrols.play();
            }
            listBoxMusic.SelectedIndex = index;
        }

        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_Load(object sender, EventArgs e)
        {
            btnControlMusic.Enabled = false;
            btnStopMusic.Enabled = false;
            btnPreviousSong.Enabled = false;
            btnNextSong.Enabled = false;
        }

        /// <summary>
        /// 音量+
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAddVolume_Click(object sender, EventArgs e)
        {
            MediaPlayer.settings.volume += 5;
        }

        /// <summary>
        /// 音量-
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnReduceVolume_Click(object sender, EventArgs e)
        {
            MediaPlayer.settings.volume -= 5;
        }

        /// <summary>
        /// 点击静音或放音
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void label1_Click(object sender, EventArgs e)
        {
            if (label1.Tag.ToString() == "1")
            {
                // 静音
                MediaPlayer.settings.mute = true;
                label1.Image = Image.FromFile(@"C:\Users\CC\Desktop\picture\开跑.jpg");
                label1.Tag = "0";
            }
            else if (label1.Tag.ToString() == "0")
            {
                // 放音
                MediaPlayer.settings.mute = false;
                label1.Image = Image.FromFile(@"C:\Users\CC\Desktop\picture\王有胜gif.gif");
                label1.Tag = "1";
            }
        }

        /// <summary>
        /// 观察 歌曲的播放时间 并且自动播放下一首
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer1_Tick(object sender, EventArgs e)
        {
            // 歌曲正在播放中
            if (MediaPlayer.playState == WMPLib.WMPPlayState.wmppsPlaying)
            {
                label2.Text = MediaPlayer.currentMedia.duration + "\r\n"
                          + MediaPlayer.currentMedia.durationString + "\r\n"
                          + MediaPlayer.Ctlcontrols.currentPosition + "\r\n"
                          + MediaPlayer.Ctlcontrols.currentPositionString;

                double d1 = double.Parse(MediaPlayer.currentMedia.duration.ToString());
                double d2 = double.Parse(MediaPlayer.Ctlcontrols.currentPosition.ToString()) + 1;
                // 如果接受则下一曲
                if (d1 <= d2)
                {
                    btnNextSong_Click(sender, e);
                }
            }
        }

        // 存储时间
        List<double> listTime = new List<double>();
        // 存储歌词
        List<string> listLrcText = new List<string>();
        /// <summary>
        /// 负责歌词的显示
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer2_Tick(object sender, EventArgs e)
        {
            if (MediaPlayer.playState == WMPLib.WMPPlayState.wmppsPlaying)
            {
                double currentTime = double.Parse(MediaPlayer.Ctlcontrols.currentPosition.ToString());
                //Console.WriteLine(currentTime);
                for (int i = 0; i < listTime.Count; i++)
                {
                    if (currentTime > listTime[listTime.Count - 1])
                    {
                        break;
                    }
                    if (currentTime > listTime[i] && currentTime < listTime[i + 1])
                    {
                        label3.Text = listLrcText[i];
                        break;
                    }
                }
            }
        }

        /// <summary>
        /// 解析歌词 保存在集合中
        /// </summary>
        /// <param name="lrcPath"></param>
        private void DoLrcFile(string lrcPath)
        {
            listTime.Clear();
            listLrcText.Clear();
            string[] musicString = File.ReadAllLines(lrcPath, Encoding.UTF8);
            foreach (string item in musicString)
            {
                string[] TimeAndText = item.Split(new char[] { '[', ']' }, StringSplitOptions.RemoveEmptyEntries);
                //如果是空行，则直接跳过，读下一行
                if (TimeAndText.Length == 0)
                {
                    continue;
                }
                string[] times = TimeAndText[0].Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
                if (times.Length != 0)
                {
                    if (double.TryParse(times[0], out double result))
                    {
                        double time;
                        if (times.Length == 1)
                        {
                            time = double.Parse(times[0]) * 60;
                        }
                        else
                        {
                            if (double.TryParse(times[1], out double result1))
                            {
                                time = double.Parse(times[0]) * 60 + double.Parse(times[1]);
                            }
                            else
                            {
                                time = double.Parse(times[0]) * 60;
                            }
                        }
                        listTime.Add(time);

                        if (TimeAndText.Length == 1)
                        {
                            listLrcText.Add(" ");
                        }
                        else
                        {
                            listLrcText.Add(TimeAndText[1]);
                        }
                    }
                }
            }
        }
    }
}
